package com.wiz.web.controllor;

import java.io.BufferedOutputStream;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wiz.web.service.DownService;

@Controller
@RequestMapping("/down")
public class DownControllor extends BaseControllor{

	@Resource
	private DownService downService;
	
	@RequestMapping(value = "/account", method = RequestMethod.POST)
	public void getMemberAccountHistroyList(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "params") String member,
			@RequestParam(value = "stationId") String stationId,
			HttpSession session, Model model) throws Exception{
		download(request,response,downService.getAccountHistory(stationId, member),"account");
	}
	
	@RequestMapping(value = "/point", method = RequestMethod.POST)
	public void getMemberPointHistroyList(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "params") String member,
			@RequestParam(value = "stationId") String stationId,
			HttpSession session, Model model) throws Exception{
		download(request,response,downService.getPointHistory(stationId, member),"point");
	}
	
	@RequestMapping(value = "/order", method = RequestMethod.POST)
	public void getFuellingOrderList(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "params") String order,
			@RequestParam(value = "stationId") String stationId,
			HttpSession session, Model model) throws Exception{
		download(request,response,downService.getFuellingOrder(stationId, order),"order");
	}
	
	private void download(HttpServletRequest request,HttpServletResponse response,
			HSSFWorkbook data,String fileName) throws Exception {
		response.setContentType("octets/stream;charset=UTF-8");
		response.addHeader("Content-Disposition","attachment;filename="+fileName+".xls");
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		data.write(outputStream);
		outputStream.flush();
		outputStream.close();
	}
}
